<?php defined('SYSPATH') or die('No direct script access.'); ?>
<div style="float:left;width:280px;">
    <img src="/images/ajax-bar-loader.gif" alt="loading..." title="Loading" id="progressbarCats"/>
<div class="grey demo-container">
    <?php
    //вывод категорий
    $count = 0;
    function printCat($cat)
    {
        if(strlen($cat['Name'])>30)
            echo '<li><a style = "font-size:80%" href="/shop/cat/', $cat['id'], '" >', $cat['Name'], '</a>';
        else
            echo '<li><a href="/shop/cat/', $cat['id'], '" >', $cat['Name'], '</a>';
        if(!count($cat['children']))  // если не корневая
            echo '</li>';
        else                       // если корневая
        {
            echo '<ul>';
            foreach($cat['children'] as $cat)
               printCat($cat);
            echo '</ul></li>';
        }
        $count = strlen($cat['Name']);
    }
    echo '<ul id="drilldown-2" style="height:800px;">';
    foreach ($cattree as $cat)
        printCat($cat);
    echo '</ul>';
    ?>

</div>
</div>


<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
    $(function() {
        $( "#head_service_search_query" ).autocomplete({source: "/ajax/autoComplete"});
    });
</script>

<div style="float:right;width:620px;">
<div class="head-container" style="padding-left: 0;padding-right: 2%;">
     <select id="catId" style="position: relative; top: -25px;float: right;z-index: 2">
        <option value="0">All categories</option>
    <?php
    foreach ($cats as $catId => $catName)
        echo '<option value="', $catId, '">', $catName, '</option>';
    ?>
    </select>
    <div class="multibar">
        <div class="search">
            <div class="search-bar" style="height: 85px;">
                <div class="search-form">
                    <input type="hidden" id="hidcat" value="<?php echo $hidcat;?>">
                    <input type="hidden" id="pageNum" value="1">
                        <div class="search-field-border">
                            <div class="search-field" >
                                <input type="text" name="query" value=""
                                       onkeyup="$('#pageNum').val(1)"
                                       style="width:90%;border-width:0;z-index:2;"
                                       id="head_service_search_query" class="query" >
                            </div>
                        </div>
                        <input type="button" value="Search" class="submit" id="Searching"><br>

                        <div style="width: 100%; display: block; text-align: right;margin-top: 8px; display: none ">
                            <a href="javascript:void(0); " id="refPar"
                                onclick="ShowForm(this)">Additional Search Parameters</a>
                        </div>

                        <img src="/images/ajax-bar-loader.gif" alt="loading..."
                             title="Loading" id="progressbar"
                             style="float:right;display:none;margin-right: 35%; "/>
                        
            </div>
                <div id="Parametrs" class="Parametrs" align="center" style="display: none; margin-top: 35px;">

                    <table style="width:94%;margin-top: 20px;">
                        <tr>
                            <td>
                                <lable>Title</lable>
                                <input type="text" name="Title" value="" id="Title">
                            </td>
                            <td>
                                <lable>Manufacturer</lable>
                                <input type="text" name="Manufacturer" value="" id="Manufacturer">
                            </td>
                            <td>
                                <lable>MaxPrice</lable>
                                <input type="text" name="MaxPrice" value="" maxlength="10" id="MaxPrice" size="4"
                                       onkeyup="validForm(this)">
                            </td>
                            <td>
                                <lable>MinPrice</lable>
                                <input type="MinPrice" name="MinPrice" value="" maxlength="10" id="MinPrice" size="4"
                                       onkeyup="validForm(this)">
                            </td>
                        </tr>
                    </table>
                    <style>
                        #Parametrs table tr td input{
                            z-index:2;
                            padding: 1px 5px;
                            height: 23px;

                            background: none repeat scroll 0 0 #FFFFFF;
                            border-radius: 5px 5px 5px 5px;
                            box-shadow: 0 1px 4px 1px #CCCCCC inset;
                        }
                    </style>
                </div>
                <!--<span id="msg">Please enter the number</span><br />-->
            </div>
        </div>
    </div>
    
    
    <div id="searchResults"><!-- search results --></div>
         
</div>
</div>
<script type="text/javascript">
    function validForm(f) {
    // Если введено число, то скрываем предупреждение
    if (parseFloat(f.value)||f.value=="")
    {
        document.getElementById("msg").style.display = "none";
        document.getElementById("Searching").style.display = "inline";
    }
    // В противном случае отображаем предупреждение
    else {
            document.getElementById("msg").style.display = "inline";
            document.getElementById("Searching").style.display = "none";
        }
   }
   
    var adm = {
        /* добавление на главную (todo=1), удаление с нее (todo=0)*/
        mainpage: function (asin, todo){            
            $.post('/ajax/productOnMainPage', {product : asin, main: todo },
                function(){ document.location.href= '/'; }
            ),
            'json';
        },
        /* для формирования div одного товара */
        item: function(ASIN, main, model, title, price, src, wList){
            return "<div class=\"product-item\">"
                    + (
                    wList == 1 ? /* показываем кнопку добавления в вишлист если нужно */
                    (
                    "<form class='AddToWishListSmall' method='post' action='/shop/wishlist'>"
                        + "<input type='hidden' name='asin' value='" + ASIN + "'/>"
                        + "<input id='buttonAdd' type='image' src='/images/AddToWishListSmall.png'/></form>"
                    )
                    : "")
                    

                    + (main == -1 ? "" : (
                       "<button class=\"bmp\" asin='"
                        + ASIN + "' todo='"
                        + (main == 1 ? "0'>x" :  "1'>Add to main page")
                        +"</button>"
                   ))
                    + "<a href=\"/shop/product/" + ASIN + "\">"
                    + "<img alt='' src=\"" + src + "\"/>"
                    + title + "</a><br />"
                    + (model != " - " ? ("<br />" + model) : "")
                    + "<br />"
                    
                    + "<br />Price: " + price
                    + "</div>";
        }
    };

    $("#refPar").click(
            function ShowForm(f) {
                if ($(this).html() != 'Hide Parameters'){
                    $('.search-bar').css('height','135px');
                    $(this).html('Hide Parameters');
                }
                else
                {
                    $('.search-bar').css('height','85px');
                    $(this).html('Additional Search Parameters');
                }


                document.getElementById("Title").value = "";
                document.getElementById("Manufacturer").value = "";
                document.getElementById("MaxPrice").value = "";
                document.getElementById("MinPrice").value = "";
                if (document.getElementById("Parametrs").style.display == "inline")
                    document.getElementById("Parametrs").style.display = "none";
                else document.getElementById("Parametrs").style.display = "inline";
            }
    );
    
$(document).ready(function(){

    function hookTxt(){
        var hook = $("#dd-header-0").find("h3");
        if($(hook).html() != null && $(hook).html() != 'Select Category')
            $(hook).html('');
    }
    hookTxt();

    $("a").click('hookTxt');

    /*document.getElementById("Parametrs").style.display = "none";
    document.getElementById("msg").style.display = "none";*/
    <?php if(isset($defined) && is_array($defined) && count($defined)):?>

        var data = <?php echo json_encode(array_values($defined));?>;
        var search = "";
        $(data).each(function(i, v){
            if(typeof(v) != "number" && typeof(v) != "string"){
                search += window.adm.item(v.ASIN, <?php echo $admin ? '1' : '-1';?>, v.model, v.title, v.price, v.src, v.wList);
            }
        });
        $("#searchResults").html(search);
        $('.bmp').click(function(){
            $(this).hide();
            $(this).parent().append('<img src="/images/ajax-bar-loader.gif" alt="loading..."/>');
            window.adm.mainpage($(this).attr('asin'), $(this).attr('todo'))
        });
        
    <?php endif;?>

    function searchIt(){

        $("#searchResults").html('');
        $("#progressbar").show();
        var c = $("#hidcat").val();
        if(c == 'nocat'){
            c = $("#catId").val();
        }
        $.post('/ajax/search',
            {
                query : $("#head_service_search_query").val(),
                page: $("#pageNum").val(),
                cat: c,
                Title: $("#Title").val(),
                Manufacturer: $("#Manufacturer").val(),
                MaxPrice: $("#MaxPrice").val(),
                MinPrice: $("#MinPrice").val() 
            },

            function (data){
                var search;/* - search result div contents */
                if(typeof(data) == "string"){
                    search = data;/* - error string */
                }else{
                    search = "";
                    $(data).each(function(i, v){
                        if(typeof(v) != "number" && typeof(v) != "string"){
                            search += window.adm.item(
                                v.ASIN, v.main, v.model, v.title, v.price, v.src, v.wList);
                        }else{
                            /* pagination */
                            var countPages = parseInt(v);
                            if(countPages > 1){                            
                                var pagin = "<div class='pagination'>Pages: ";
                                var i = parseInt($("#pageNum").val());

                                if(i > 1){
                                    if(i > 2){
                                        pagin += "<a href='javascript:void(0);' "
                                            + "onclick='$(\"#pageNum\").val(1);"
                                            + "$(\"#Searching\").trigger(\"click\");'>"
                                            + "First</a> ";
                                    }
                                    pagin += "<a href='javascript:void(0);' "
                                            + "onclick='$(\"#pageNum\").val(" + (i-1) + ");"
                                            + "$(\"#Searching\").trigger(\"click\");'>"
                                            + "" + (i-1) + "</a> ";
                                }
                                pagin += " <strong>" + i + "&nbsp;&nbsp;</strong>";
                                if(i < countPages){
                                    pagin += "<a href='javascript:void(0);' "
                                            + "onclick='$(\"#pageNum\").val(" + (i+1) + ");"
                                            + "$(\"#Searching\").trigger(\"click\");'>"
                                            + "" + (i+1) + "</a> ";
                                }
                                if(i+1 < countPages){
                                    pagin += "<a href='javascript:void(0);' "
                                            + "onclick='$(\"#pageNum\").val(" + (i+2) + ");"
                                            + "$(\"#Searching\").trigger(\"click\");'>"
                                            + "" + (i+2) + "</a> ";
                                }
                                if(i+2 < countPages){
                                    pagin += "<a href='javascript:void(0);' "
                                            + "onclick='$(\"#pageNum\").val(" + (i+3) + ");"
                                            + "$(\"#Searching\").trigger(\"click\");'>"
                                            + "..." + "</a> ";
                                }

                                pagin += "</div>";
                                search = pagin + search + pagin;
                            }
                        }
                    });
                    if(search == ""){/* not found */
                        search = "<h2 style=\" display: block;float: none;position: relative;text-align: center;top: 75px;z-index:0;\">No items found.</h2>";
                    }

                }
                $("#progressbar").hide();
                $("#searchResults").html(search);
                
                $('.bmp').click(function(){
                    $(this).hide();
                    $(this).parent().append('<img src="/images/ajax-bar-loader.gif" alt="loading..."/>');
                    window.adm.mainpage($(this).attr('asin'), $(this).attr('todo'))
                });
            },
            'json'
        );
    }
    
    $("#Searching").click(searchIt);
        
    if($("#hidcat").val() != 'nocat'){
        $('#catId').hide();
        searchIt();
    }
    
});
</script>